package org.dei.perla.aggregates;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Iterator;

import org.dei.perla.parser.expressions.Constant;
import org.dei.perla.parser.expressions.ConstantCastException;
import org.dei.perla.sys.query.llqruntime.datastructures.Buffer;
import org.dei.perla.sys.query.llqruntime.datastructures.Record;
public class Variance {
	public static double variance(Buffer buffer, String fieldName) throws ConstantCastException {
		ArrayList<Record> list = buffer.getBuffer();
		Iterator<Record> it = list.iterator();
		
		double[] data = new double[list.size()];
		int i =0;
		Class<?> type=null;
		while(it.hasNext()){
			Record t = it.next();
			type = t.getRecordStructure().get(fieldName).getFieldType();
			data[i]=t.getField(fieldName).getValueFloat();
			// System.out.println("ID: "+t.getField("ID")+" - TS: "+t.getField("TS")+" - TEMP : "+t.getField("TEMP"));
		    i++;
		}
		double variance = variance(data);
//		Constant result=null;
//		try {
//			//result = (Constant)(type.getConstructor(String.class).newInstance(String.valueOf(variance)));
//			Constructor<?> nameConstructor= type.getConstructor(String.class);  
//			result = (Constant) nameConstructor.newInstance(String.valueOf(variance));
//
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
		return variance;
	}
	public static double variance(double[] data) {
		double sumX = 0;
		double sumXsquare = 0;
		int len = data.length;
		double mean = 0;
		double variance = 0;
		for (int i = 0; i < data.length; i++) {
			sumX += data[i];
		//	System.out.println(sumX);
			sumXsquare += data[i] * data[i];
			System.out.println("Dato : "+data[i]+ "Sum : "+sumX+ "sumXsquare: "+sumXsquare);
		}
		mean = sumX / len;
		variance = mean * mean - sumXsquare / (len * len);
		return variance;
	}
}
